package com.lincoln.framework.utils;

import com.lincoln.framework.bean.Geolocation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class GeolocationUtils {

	private static final int STATUS_SUCCESS = 0;

	private static FrameworkLogger logger = FrameworkLogger.initFrameworkLogger(GeolocationUtils.class);

	/**
	 * 地理位置接口地址
	 */
	private static final String API_GEOCODER_URL = "http://api.map.baidu.com/geocoder/v2/";

	/**
	 * GPS 转 百度坐标
	 */
	private static final String API_GEOCONV_URL = "http://api.map.baidu.com/geoconv/v1/";

	/**
	 * ip获取地理位置接口
	 */
	private static final String API_LOCATION_API = "http://api.map.baidu.com/location/";

	/**
	 * 接口秘钥
	 */
	private static final String API_KEY = "XoZYVVPR337Ot2AOBfUqLEum";

	/**
	 * 根据经纬度获取城市信息
	 */
	public static String getCity(Double latitude, Double longitude) {
		String city = "";
		Geolocation geolocation = getLocation(latitude, longitude);
		if (geolocation.getCity() != null) {
			if (geolocation.getCity().equals(geolocation.getProvince())) {
				city = geolocation.getCity();
			} else {
				city = geolocation.getProvince() + geolocation.getCity();
			}
		}
		return city;
	}

	/**
	 * 根据经纬度获取城市信息
	 */
	public static String getCity(String coords) {
		String[] values = coords.split(",");
		if (values.length > 1) {
			double latitude = Double.parseDouble(values[0]);
			double longitude = Double.parseDouble(values[1]);
			return getCity(latitude, longitude);
		}
		return "";
	}

	/**
	 * 根据经纬度获取地理位置
	 */
	public static Geolocation getLocation(Double latitude, Double longitude) {
		Geolocation geolocation = new Geolocation();
		try {
			geolocation.setLatitude(latitude);
			geolocation.setLongitude(longitude);
			StringBuffer jsonBuffer = new StringBuffer();
			String urlString = API_GEOCODER_URL + "?ak=" + API_KEY + "&location=" + latitude + "," + longitude + "&coordtype=wgs84ll&output=json&pois=0";
			URL url = new URL(urlString);
			URLConnection urlConnection = url.openConnection();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				jsonBuffer.append(line);
			}
			try {
				JSONObject jsonObject = JSONObject.fromObject(jsonBuffer.toString());
				if (jsonObject.get("status") != null && (Integer) jsonObject.get("status") == STATUS_SUCCESS) {
					JSONObject result = (JSONObject) jsonObject.get("result");
					if (result != null) {
						geolocation.setAddress(result.get("formatted_address").toString());
						JSONObject addressComponent = (JSONObject) result.get("addressComponent");
						if (addressComponent != null) {
							geolocation.setProvince(addressComponent.get("province").toString());
							geolocation.setCity(addressComponent.get("city").toString());
							geolocation.setDistrict(addressComponent.get("district").toString());
							geolocation.setStreet(addressComponent.get("street").toString());
							geolocation.setStreetNumber(addressComponent.get("street_number").toString());
						}
					}
				}
			} catch (Exception ex) {
				logger.error(ex.getMessage(), ex);
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
		return geolocation;
	}

	public static Geolocation getLocation(String ip) {
		Geolocation geolocation = new Geolocation();
		try {
			geolocation.setIp(ip);
			String urlString = API_LOCATION_API + "ip?ak=" + API_KEY + "&ip=" + ip + "&coor=bd09ll";
			StringBuffer jsonBuffer = new StringBuffer();
			URL url = new URL(urlString);
			URLConnection urlConnection = url.openConnection();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				jsonBuffer.append(line);
			}
			try {
				JSONObject jsonObject = JSONObject.fromObject(jsonBuffer.toString());
				if (jsonObject.get("status") != null && (Integer) jsonObject.get("status") == STATUS_SUCCESS) {
					JSONObject result = (JSONObject) jsonObject.get("content");
					if (result != null) {
						geolocation.setAddress(result.get("address").toString());
						JSONObject point = (JSONObject) result.get("point");
						JSONObject addressDetail = (JSONObject) result.get("address_detail");
						geolocation.setLongitude(Double.valueOf(point.get("x").toString()));
						geolocation.setLatitude(Double.valueOf(point.get("y").toString()));
						geolocation.setProvince(addressDetail.get("province").toString());
						geolocation.setCity(addressDetail.get("city").toString());
						geolocation.setStreet(addressDetail.get("street").toString());
						geolocation.setStreetNumber(addressDetail.get("street_number").toString());
						geolocation.setDistrict(addressDetail.get("district").toString());

					}
				}
			} catch (Exception ex) {
				logger.error(ex.getMessage(), ex);
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
		return geolocation;
	}

	/**
	 * GPS坐标转百度坐标
	 */
	public static JSONObject geoConvert(Double latitude, Double longitude) {
		JSONObject geoLocation = new JSONObject();
		geoLocation.put("latitude", latitude);
		geoLocation.put("longitude", longitude);
		try {
			StringBuffer jsonBuffer = new StringBuffer();
			String urlString = API_GEOCONV_URL + "?ak=" + API_KEY + "&coords=" + longitude + "," + latitude;
			URL url = new URL(urlString);
			URLConnection urlConnection = url.openConnection();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				jsonBuffer.append(line);
			}
			JSONObject jsonObject = JSONObject.fromObject(jsonBuffer.toString());
			if (jsonObject.get("status") != null && (Integer) jsonObject.get("status") == STATUS_SUCCESS) {
				JSONArray result = JSONArray.fromObject(jsonObject.get("result"));
				if (result.size() > 0) {
					JSONObject geo = result.getJSONObject(0);
					if (geo.get("x") != null && geo.get("y") != null) {
						geoLocation.put("longitude", geo.get("x"));
						geoLocation.put("latitude", geo.get("y"));
					}
				}
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
		return geoLocation;
	}
}
